package com.g9.blog.service.impl;

import com.g9.blog.entity.Article;
import com.g9.blog.entity.ArticleSort;
import com.g9.blog.entity.Sort;
import com.g9.blog.repository.ArticleSortRepository;
import com.g9.blog.repository.SortRepository;
import com.g9.blog.service.SortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: Graycat
 * @Date: 2020/9/14 19:34
 * Create by lwj.
 */
@Service
@Transactional
public class SortServiceImpl implements SortService {

    @Autowired
    private SortRepository sortRepository;
    @Autowired
    private ArticleSortRepository articleSortRepository;

    // 增加或修改分类
    public void save(Sort sort) {
        sortRepository.save(sort);
    }

    // 根据id删除分类
    public void deleteById(int sortId) {
        sortRepository.deleteById(sortId);
    }

    // 查询所有分类信息
    public List<Sort> findAll() {
        return sortRepository.findAll();
    }

    // 保存文章-分类进关联表中
    public void saveToConnet(int articleId, int sortId) {
        ArticleSort articleSort = new ArticleSort();
        articleSort.setArticleId(articleId);
        articleSort.setSortId(sortId);
        articleSortRepository.save(articleSort);
    }

    // 根据id查找分类信息。
    public Sort findById(int id) {
        return sortRepository.findById(id);
    }

    // 根据分类id查找该分类下的所有文章 --
    public List<Article> findAllArticleBySortId(int sortId) {
        List<Article> articleList = articleSortRepository.findAllArticleBySortId(sortId);
        return articleList;
    }

    @Override
    public boolean isExist(int articleId, int sortId) {
        ArticleSort sort = articleSortRepository.findByArticleIdAndSortId(articleId,sortId);
        if (sort != null) {
            return true;
        }
        return false;
    }
}
